﻿using WebApp.Models;
using WebApp.ViewModels;
using WebApp.ViewModels.Manage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApp.BLL;
using WebApp.BLL.Base;
using WebApp.DAL;
using System.Web;
using WebApp.Common;

namespace WebApp.BLL.Manage
{
    public class S_user_loginerrorService:BaseService<S_user_loginerror>
    {
        #region DAL

        #endregion

        #region 构造

        public S_user_loginerrorService() : base(new S_user_loginerrorRepository()) { }

        #endregion

        #region LoginError

        public void LoginError(string clientid, int userid, string username, string comments = "")
        {
            S_user_loginerror errorlog = this.CurrentRepository.Entities.FirstOrDefault(p => p.Clientid == clientid && p.Username == username);
            if (errorlog == null)
            {
                errorlog = new S_user_loginerror();
                errorlog.User_id = userid;
                errorlog.Username = username;
                errorlog.Errortimes = 1;
                errorlog.Comments = comments;
                errorlog.Oprttime = DateTime.Now;
                errorlog.Ip = WebUtils.getIPAddress(HttpContext.Current);
                errorlog.Oprttype = 1;
                errorlog.Clientid = clientid; //唯一标示
                this.CurrentRepository.Add(errorlog);
            }
            else
            {
                errorlog.User_id = userid;
                errorlog.Username = username;
                errorlog.Errortimes += 1;
                errorlog.Comments = comments;
                errorlog.Oprttime = DateTime.Now;
                errorlog.Ip = WebUtils.getIPAddress(HttpContext.Current);
                this.CurrentRepository.Update(errorlog);
            }
        }

        #endregion

        public int getErrorNumber(string clientid, string username)
        {
            var item = this.CurrentRepository.Entities.FirstOrDefault(p => p.Clientid == clientid && p.Username == username);
            if (item == null)
            {
                return 0;
            }
            else
            {
                return item.Errortimes;
            }
        }

        public int getErrorNumber(string clientid)
        {
            var errors = 0;
            var list = this.CurrentRepository.Entities.Where(p => p.Clientid == clientid).Select(p => p.Errortimes);
            foreach (var item in list)
            {
                errors += item;
            }
            return errors;
        }

        public void ClearErrorNumber(string clientid)
        {
            var list = this.CurrentRepository.Entities.Where(p => p.Clientid == clientid).ToList();
            foreach (var item in list)
            {
                item.Errortimes = 0;
                this.CurrentRepository.Update(item);
            }
        }

    }
}
